package com.lc.user.express.my;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.lc.user.express.BaseSecondActivity;
import com.lc.user.express.MainActivity;
import com.lc.user.express.R;
import com.lc.user.express.app.AppContext;
import com.lc.user.express.httpserver.GetFgetPayPwd;
import com.lc.user.express.httpserver.GetLogin;
import com.lc.user.express.httpserver.GetVerfyCode;
import com.lc.user.express.ordering.OrderInfoCompleteActivity;
import com.lc.user.express.utils.ExampleUtil;
import com.lc.user.express.utils.GetToast;
import com.lc.user.express.utils.PublicMethod;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.yun.YunAction;

import java.util.LinkedHashSet;
import java.util.Set;

import cn.jpush.android.api.TagAliasCallback;
import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/2/29. 登录 验证手机号码 type: TYPE_LOGIN登录 TYPE_VERIFY 验证手机号码
 */
public class LoginActivity extends BaseSecondActivity {
    public static final String TAG = "JPush";
    public static final int TYPE_LOGIN = 0x11;//登录
    public static final int TYPE_VERIFY = 0x12;//验证手机号码
    private EditText et_mobile;//手机号
    private EditText et_verify_code;//验证码
    private TextView tv_getcode;//获取验证码
    private TimeCount time;//倒计时
    private int type = TYPE_LOGIN;//标志位
    private String code = "";
    private String mobilenumber = "";
    private TextView tv_public;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    private void initView() {
        type = getIntent().getFlags();
        setTitle(type == TYPE_VERIFY ? "验证手机号码" : "登录");
        et_mobile = (EditText) findViewById(R.id.et_mobile);
        et_verify_code = (EditText) findViewById(R.id.et_verify_code);
        tv_getcode = (TextView) findViewById(R.id.tv_getcode);
        tv_getcode.setOnClickListener(this);
        tv_public = ((TextView) findViewById(R.id.tv_public));
        tv_public.setOnClickListener(this);
        tv_public.setText(type == TYPE_VERIFY ? "下一步" : "登录");

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_public:
                if (!ifCommit()) {
                    return;
                }
                if (type == TYPE_VERIFY) {
                    show(SetPayPasswordActivity.class, SetPayPasswordActivity.TYPE_FORGET);
                } else {
                    login();
                }

                break;
            case R.id.tv_getcode:
                if (TextUtils.isEmpty(et_mobile.getText().toString())) {
                    GetToast.useString(cnt, "请输入您的手机号码");
                    return;
                }
                if (!PublicMethod.isMobilePhone(et_mobile.getText().toString())) {
                    GetToast.useString(cnt, "请输入正确的手机号码");
                    return;
                }
                if (type == TYPE_VERIFY) {
                    getForgetCode();
                } else {
                    getCode();
                }
                break;
        }
    }

    private void getCode() {
        new GetVerfyCode(et_mobile.getText().toString().trim(), new AsyCallBack<GetVerfyCode.Info>() {
            @Override
            public void onSuccess(String toast, int type, GetVerfyCode.Info info) throws Exception {
                mobilenumber = et_mobile.getText().toString().trim();
                code = info.code;
                time = new TimeCount(60000, 1000, false);
                time.start();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                if (!TextUtils.isEmpty(toast)) GetToast.useString(cnt, toast);
            }
        }).execute(cnt);

    }

    private void getForgetCode() {
        new GetFgetPayPwd(AppContext.myPreferences.getUid(), et_mobile.getText().toString().trim(), new AsyCallBack<GetFgetPayPwd.Info>() {
            @Override
            public void onSuccess(String toast, int type, GetFgetPayPwd.Info info) throws Exception {
                mobilenumber = et_mobile.getText().toString().trim();
                code = info.code;
                time = new TimeCount(60000, 1000, false);
                time.start();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                if (!TextUtils.isEmpty(toast)) GetToast.useString(cnt, toast);
            }
        }).execute(cnt);

    }

    private boolean ifCommit() {
        if (TextUtils.isEmpty(et_mobile.getText().toString())) {
            GetToast.useString(cnt, "请输入您的手机号码");
            return false;
        } else if (!PublicMethod.isMobilePhone(et_mobile.getText().toString())) {
            GetToast.useString(cnt, "请输入正确的手机号码");
            return false;
        } else if (TextUtils.isEmpty(et_verify_code.getText().toString())) {
            GetToast.useString(cnt, "请输入验证码");
            return false;
        } else if (!code.equals(et_verify_code.getText().toString())) {
            GetToast.useString(cnt, "请输入正确的验证码");
            return false;
        } else if (!mobilenumber.equals(et_mobile.getText().toString())) {
            GetToast.useString(cnt, "请输入和验证码相匹配的手机号");
            return false;
        }
        return true;
    }

    private void login() {
        new GetLogin(et_mobile.getText().toString().trim(), new AsyCallBack<GetLogin.Info>() {
            @Override
            public void onSuccess(String toast, int type, GetLogin.Info info) throws Exception {
                YunAction.getInstance().login(LoginActivity.this, info.userid);
                AppContext.myPreferences.setUid(info.userid);
                Log.i("userid", info.userid);
                AppContext.myPreferences.setIsLogin(true);
                AppContext.myPreferences.setUserName(et_mobile.getText().toString());

                EventBus.getDefault().post(0);
                startActivity(new Intent(LoginActivity.this,MainActivity.class));

             //   finish();
            /*    if (OrderManagementFragment.onRefreshOrderData != null) {
                    OrderManagementFragment.onRefreshOrderData.onRefresh();
                }*/

                if (MyFragment.onReFresh != null) {
                    MyFragment.onReFresh.onRefresh();
                }
                if (MainActivity.onLoginListener != null) {
                    MainActivity.onLoginListener.onLogin(true);
                }
                if (OrderInfoCompleteActivity.onPointMoney != null) {
                    OrderInfoCompleteActivity.onPointMoney.onPoint();
                }
//                if (JPushInterface.isPushStopped(cnt)) {
//                    JPushInterface.resumePush(cnt);
//                }
                if (!TextUtils.isEmpty(AppContext.myPreferences.getUid())) {
//                    JPushInterface.setAlias(cnt, AppContext.myPreferences.getUid(), mAliasCallback);
                }


            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                if (!TextUtils.isEmpty(toast)) GetToast.useString(cnt, toast);


            }
        }).execute(cnt);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (MainActivity.onLoginListener != null) {
            MainActivity.onLoginListener.onLogin(false);
        }
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval, boolean ten) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            tv_getcode.setClickable(true);
            tv_getcode.setText("获取验证码");
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            tv_getcode.setClickable(false);
            tv_getcode.setText(millisUntilFinished / 1000 + "s");

        }
    }

    private void setTag() {

        String tag = AppContext.myPreferences.getUid();

        // 检查 tag 的有效性
        if (TextUtils.isEmpty(tag)) {

            return;
        }

        // ","隔开的多个 转换成 Set
        String[] sArray = tag.split(",");
        Set<String> tagSet = new LinkedHashSet<String>();
        for (String sTagItme : sArray) {
            if (!ExampleUtil.isValidTagAndAlias(sTagItme)) {

                return;
            }
            tagSet.add(sTagItme);
        }

        //调用JPush API设置Tag
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tagSet));

    }

    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;


    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
//                case MSG_SET_ALIAS:
//                    Log.d(TAG, "Set alias in handler.");
//                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
//                    break;

                case MSG_SET_TAGS:
                    Log.d(TAG, "Set tags in handler.");
//                    JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mTagsCallback);
                    break;

                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };
    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        Log.i(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }

            Log.i(TAG, logs);
        }

    };
    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
                    } else {
                        Log.i(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }

            Log.i(TAG, "==" + getApplicationContext());
        }

    };
}
